package com.evon.yardmanagement.security;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.hibernate.Hibernate;

import com.evon.yardmanagement.dao.UserDAO;
import com.evon.yardmanagement.model.Role;
import com.evon.yardmanagement.model.User;

public class SecurityRealm extends AuthorizingRealm {

	private UserDAO userDAO;

	private static final Logger log = Logger.getLogger(SecurityRealm.class);

	// DAO instance for retrieving user information.

	public SecurityRealm() {
		userDAO = new UserDAO();
	}

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principals) {
		String userId = (String) principals.fromRealm(getName()).iterator().next();
		System.err.println("uerd ---"+userId);
		User user = userDAO.findUser(userId);
		
		//Avoid lazy loading later, eagerly load collection
		Hibernate.initialize(user.getAccessibleYards());
		//Store the user object in Session
		SecurityUtils.getSubject().getSession().setAttribute("CURRENT_USER", user);
		if (user != null) {
			SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
			for (Role role : user.getRoles()) {
				info.addRole(role.getName());
				info.addStringPermissions(role.getAllowedActionName());
			}
			
			//Set the vendor Id, Allowed Yard Id in session.
			return info;
		} else {
			return null;
		}
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token) throws AuthenticationException {
		UsernamePasswordToken authcToken = (UsernamePasswordToken) token;
		User user = userDAO.findUser(authcToken.getUsername());
		if (user != null) {
			return new SimpleAuthenticationInfo(user.getUserName(), user.getPasswd(),
					getName());
		}
		return null;
	}
}